<template>
  <section>
    <div style="height:480px;margin-top: 10px;overflow-x: hidden;">
      <div>
        <template v-for="(data, index) in steps">
          <el-row
            :key="index"
            v-if="data.behavior.runSelect || flowSelectType == 'STEP_FIRST'"
          >
            <el-row class="custom-tree-node step_node ">
              <el-col :span="15" class="label_checked">
                <el-checkbox
                  :key="data.id"
                  :label="data.id"
                  v-model="data.checked"
                  @change="changeNodeClick"
                  >{{ data.nodeName }}
                </el-checkbox>
              </el-col>
              <el-col
                v-if="data.type !== 'copy' && flowSelectType == 'STEP_USER'"
                :span="9"
                class="node_item"
              >
                <el-date-picker
                  v-model="data.limitSelectTime"
                  type="date"
                  :disabled="!data.limitTime"
                  style="width:95%"
                  value-format="yyyy-MM-dd"
                  placeholder="选择处理日期"
                >
                </el-date-picker>
              </el-col>
              <el-row>
                <el-col style="width: 99%;margin-left: 32px">
                  <template v-if="flowSelectType == 'STEP_USER'">
                    <setp-user-select
                      :user-range="data.behavior.selectRange"
                      :run-select="data.behavior.runSelect"
                      :is-mul-select="true"
                      v-model="data.member"
                    >
                    </setp-user-select>
                  </template>
                  <template v-if="flowSelectType == 'STEP_FIRST'">
                    <div style="display: flex;">
                      <el-input
                        :placeholder="`请选择${data.nodeName}`"
                        v-model="data.userNames"
                        :disabled="true"
                        :style="{ flex: '1' }"
                      >
                      </el-input>
                      <el-button
                        :disabled="!data.behavior.runSelect"
                        type="primary"
                        @click="chooseStepUser({ data, index })"
                        style="position: relative;left: -32px;"
                        >选择
                      </el-button>
                    </div>
                  </template>
                </el-col>
              </el-row>
            </el-row>
          </el-row>
          <el-row :key="index" v-else>
            <el-row class="custom-tree-node step_node">
              <el-col :span="6" class="label_checked">
                <el-checkbox
                  :key="data.id"
                  :label="data.id"
                  v-model="data.checked"
                  @change="changeNodeClick"
                  >{{ data.nodeName }}
                </el-checkbox>
              </el-col>
              <el-col :span="9">
                <setp-user-select
                  :user-range="data.behavior.selectRange"
                  :run-select="data.behavior.runSelect"
                  :is-mul-select="true"
                  v-model="data.member"
                >
                </setp-user-select>
              </el-col>
              <el-col
                :span="9"
                class="node_item"
                v-if="data.type !== 'copy' && flowSelectType == 'STEP_USER'"
              >
                <el-date-picker
                  v-model="data.limitSelectTime"
                  type="date"
                  :disabled="!data.limitTime"
                  style="width:95%"
                  value-format="yyyy-MM-dd"
                  placeholder="选择处理日期"
                >
                </el-date-picker>
              </el-col>
            </el-row>
          </el-row>
        </template>
      </div>
    </div>
    <div style="margin-top: 20px;text-align: right">
      <el-button @click="executeData" type="primary"
        ><i class="el-icon-s-promotion" style="margin-right: 5px;"></i>确定
      </el-button>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      custom-class="user_select_dialog"
      title="选择"
      append-to-body
      ref="user_select_dialog"
      :visible.sync="showSelect"
    >
      <template v-if="currentData.behavior">
        <setp-user-select
          :user-range="currentData.behavior.selectRange"
          :run-select="currentData.behavior.runSelect"
          :is-mul-select="true"
          v-model="currentData.copyMember"
          :key="currentData.id"
          ref="stepSelect"
          height="300px"
        >
        </setp-user-select>
      </template>
      <div class="btn-box">
        <el-button type="primary" @click="confirmSelect">确认</el-button>
        <el-button type="info" @click="cancleSelect">取消</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import _ from "lodash";
import userRangeSelect from "./user-range-select";
import setpUserSelect from "./step-user-select";

export default {
  name: "stepSelect",
  components: {
    userRangeSelect,
    setpUserSelect
  },
  props: {
    nodes: {
      type: Array,
      default: []
    },
    // 是否多选
    isMulSelect: {
      type: Boolean,
      default: true
    },
    // 选择类型，SINGLE单选，MORE_FIRST多选 (默认选中第一个),MORE_ALL多选 (默认全部选中),MORE_NONE多选 (默认全部不选中)
    selectType: {
      type: [String],
      default: "SINGLE"
    },
    // 步骤用户选择方式(默认步骤用户同时)
    flowSelectType: {
      type: [String],
      default: "STEP_USER"
    }
  },
  data() {
    return {
      checkList: [],
      steps: [],
      checkedSteps: [],
      showSelect: false,
      currentData: {} // 当前选择的信息
    };
  },
  mounted() {
    this.initData();
    this.updateDefaultUser();
  },
  watch: {
    // nodes: {
    //   handler(val) {
    //     console.log(val);
    //     // this.initData()
    //   },
    //   deep: true
    // },
    // steps: {
    //   handler(val) {
    //     for (let i = 0; i < val.length; i++) {
    //       if (val[i].member) {
    //         val[i].checked = true;
    //       } else {
    //         val[i].checked = false;
    //       }
    //     }
    //   },
    //   deep: true
    // },
    checkedSteps: {
      handler(val) {
        if (val && val.length > 0) {
          let tem = [];
          val.map(item => {
            tem.push({
              id: item.id,
              member: item.member,
              type: item.type,
              limitTime: item.limitSelectTime
            });
          });
          this.$emit("input", tem);
        }
      },
      deep: true
    }
  },
  methods: {
    initData() {
      this.steps = _.cloneDeep(this.nodes);
      if (this.steps) {
        this.steps.map(item => {
          if (item.behavior.defaultHandler) {
            // console.log(item.behavior.defaultHandler, ":defaultHandler");
          }
          this.$set(item, "limitSelectTime", "");
          this.$set(item, "member", item.behavior.defaultHandler);
          this.$set(item, "checked", false);
          this.$set(item, "type", item.type);
        });
      }
      // console.log(this.steps, "默认值");
      this.setChecked();
    },
    // 确认数据
    confirmSelect() {
      // console.log(this.$refs.stepSelect.rightSelectUsers);
      let rightSelectUsers = this.$refs.stepSelect.rightSelectUsers;
      let userNames = this.$refs.stepSelect.userNames;
      let arr = [];
      // for(let i = 0; i < rightSelectUsers.length; i ++){
      //   arr.push(rightSelectUsers[i].name)
      // }
      this.currentData.member = this.currentData.copyMember;
      this.currentData.userNames = userNames;
      this.showSelect = false;
      if (!this.currentData.member) {
        return
      }
      if (this.selectType === "SINGLE") {
        if (this.currentData.type === "copy") {
          this.currentData.checked = true;
        } else {
          this.steps.map(item => {
            item.checked = false;
            this.currentData.checked = true;
          });
        }
      }
      // for (let i = 0; i < this.steps.length; i++) {
      //   console.log(this.steps[i])
      //   if (this.steps[i].member) {
      //     this.steps[i].checked = true;
      //   } else {
      //     this.steps[i].checked = false;
      //   }
      // }
    },
    // 默认选择用户
    updateDefaultUser() {
      let tem = { type: 1, parentId: 0 };
      let checkStatus = false;
      this.API.getOrganizeTree(tem).then(res => {
        for (let i = 0; i < this.steps.length; i++) {
          let userNames = "";
          let defaultHandler = this.steps[i].behavior.defaultHandler;
          let users = defaultHandler.split(",");
          if (users && res.data) {
            let otherUsers = [];
            users.map((item, index) => {
              let name = this.getUserNameById(res.data, item);
              if (name === undefined || name === null) {
                otherUsers.push(item);
              } else {
                if (index === users.length - 1 - otherUsers.length) {
                  userNames += name;
                } else {
                  userNames += name + ",";
                }
              }
            });
            if (otherUsers && otherUsers.length > 0) {
              this.getNameByGroupData(otherUsers);
            }
          }
          this.$set(this.steps[i], "userNames", userNames);
          this.$set(this.steps[i], 'copyMember', defaultHandler);
          if (userNames && !checkStatus) {
            checkStatus = true;
            this.$set(this.steps[i], "checked", true);
          }

          // this.steps[i].userNames = userNames;
        }
      });
    },
    getNameByGroupData(otherUsers) {
      let temGroup = { type: 0, parentId: 0, isMe: 0 };
      this.API.getWorkGroupTree(temGroup).then(res => {
        if (res.data) {
          otherUsers.map((item, index) => {
            let name = this.getUserNameById(res.data, item);
            if (index === otherUsers.length - 1) {
              this.userNames += name;
            } else {
              this.userNames += name + ",";
            }
          });
        }
      });
    },

    getUserNameById(data, item) {
      for (let i = 0; i < data.length; i++) {
        let user = data[i];
        // console.log(item)
        if (user.id === item) {
          // this.rightSelectUsers.push(user);
          // console.log(this.rightSelectUsers, '默认用户数组')
          return user.name;
        } else {
          if (user.children !== undefined) {
            let result = this.getUserNameById(user.children, item);
            if (result) {
              return result;
            }
          } else {
            continue;
          }
        }
      }
    },
    // 取消选择
    cancleSelect() {
      this.currentData.copyMember = this.currentData.member;
      this.showSelect = false;
    },
    // 选择步骤人员
    chooseStepUser(obj = {}) {
      let { data, index } = obj;
      this.currentData = data;
      this.showSelect = true;
    },
    // 根据类型，默认选择的设置
    setChecked() {
      switch (this.selectType) {
        case "MORE_FIRST":
          this.steps[0].checked = true;
          break;
        case "MORE_ALL":
          let tem = [];
          if (this.steps) {
            this.steps.map(item => {
              item.checked = true;
            });
          }
          break;
        case "MORE_NONE":
          break;
      }
      if (this.steps.length === 1) {
        this.steps[0].checked = true;
      }
    },
    //左侧多选事件
    changeNodeClick(data, node) {
      // console.log(data, node);
      let curStep = {};
      if (this.steps) {
        this.steps.map(item => {
          if (item.id === node.target.defaultValue) {
            curStep = item;
          }
        });
      }
      if (this.selectType === "SINGLE") {
        // 单选
        if (this.steps) {
          if (curStep.type === "copy") {
            this.steps.map(item => {
              if (item.id === node.target.defaultValue) {
                item.checked = data;
              }
            });
          } else {
            this.steps.map(item => {
              if (item.type !== "copy") {
                if (item.id === node.target.defaultValue) {
                  item.checked = data;
                } else {
                  item.checked = false;
                }
              }
            });
          }
        }
      } else {
        if (this.steps) {
          this.steps.map(item => {
            // console.log(item.id,node.target.defaultValue)
            if (item.id === node.target.defaultValue) {
              // item.checked = !item.checked;
            }
          });
        }
      }
      // console.log(this.steps);
    },
    executeData() {
      let val = [];
      if (this.steps) {
        this.steps.map(item => {
          if (item.checked) {
            val.push(item);
          }
        });
      }

      if (val && val.length > 0) {
        let tem = [];
        let errTip = false;
        val.map(item => {
          if (!item.member) {
            errTip = true;
            this.warning(item.nodeName + ":请至少选择一个处理者");
          }
          tem.push({
            id: item.id,
            member: item.member,
            type: item.type,
            limitTime: item.limitSelectTime
          });
        });
        if (errTip) {
          return;
        } else {
          // console.log(tem, "steps1111111111111111");
          this.$emit("input", tem);
          this.$emit("executeData", tem);
        }
      } else {
        this.warning("请至少选择一个步骤");
      }
    }
  }
};
</script>

<style lang="less" scoped>
.btn-box {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  el-button + el-button {
    margin-left: 20px;
  }
}
.stepUser.step_node {
  margin-left: 50px;
  margin-right: 50px;
}
.step_node {
  border: 1px solid #dcdfe6;
  border-radius: 3px;
  padding: 10px;
  margin-bottom: 10px;
}

.label_checked {
  height: 50px !important;
  line-height: 50px !important;
  padding-left: 10px !important;
}

.node_item {
  line-height: 50px;
  height: 50px;
}
</style>
